<template>
  <div class="basemap">
    <div id="map" class="map"></div>
  </div>
</template>

<script>
import $ from "jquery";

export default {
  data() {
    return {
      map: null,
      population: null,
      cqarea: null,
    };
  },
  mounted() {
    this.initMap();
    this.getGeoJson();
  },
  methods: {
    initMap() {
      // 重庆市经纬度 107.820952,29.839539
      // const cqp = this.$L.latLng(29.5647398, 106.5478767);
      const cqp = this.$L.latLng(30.299539, 107.820952);

      this.map = this.$L
        .map("map", {
          // 版权控件
          attributionControl: false,
          // 缩放控件
          zoomControl: false,
        })
        .setView(cqp, 7);

      // 天地图token
      const tdtToken = "810e2cf8deac0489c6bb8ee29e5d9591";
      // 天地图 影像底图
      const wmtsImg =
        "http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=" +
        tdtToken;

      this.$L
        .tileLayer(wmtsImg, {
          maxZoom: 18,
        })
        .addTo(this.map);
    },
    async getGeoJson() {
      // 引入geojson文件

      await $.getJSON("../data/json/500000.geoJson", async (data) => {
        const area = data;
        // 将人口数据 依次添加到 各区县
        await $.getJSON("../data/json/population.json", (data) => {
          const population = data.population;
          for (let i = 0; i < population.length; i++) {
            area[i].properties["population"] = population[i];
          }
        });

        this.cqarea = this.$L
          .geoJSON(area, {
            // 设置feature样式
            style: (feature) => {
              console.log(feature);
              // 必须设置异步 否则拿不到population数据
              return {
                fillColor: this.getColor(feature.properties.population),
                weight: 2,
                opacity: 1,
                color: "white",
                dashArray: "3",
                fillOpacity: 0.7,
              };
            },
            // 控制feature可见性
            filter: (feature) => {
              return true;
            },
            pointToLayer: (feature) => {
              return this.$L.marker(feature.properties.center)
            },
          })
          .addTo(this.map);
      });
    },
    // 获取填充色样式
    getColor(d) {
      return d > 1000
        ? "#800026"
        : d > 800
        ? "#BD0026"
        : d > 600
        ? "#E31A1C"
        : d > 400
        ? "#FC4E2A"
        : d > 200
        ? "#FD8D3C"
        : d > 100
        ? "#FEB24C"
        : d > 10
        ? "#FED976"
        : "#FFEDA0";
    },
  },
};
</script>

<style>
</style>